"""
@ Author:https://blog.csdn.net/silvia__y/article/details/103496571
@ File:svm_digits.py
@ Date: 2021-02-20
@ Function:Use SVM to achieve minist classification
@ Python 3.6.8

"""

from sklearn import datasets
digits = datasets.load_digits()    #加载scikit-learn自带的手写数字识别图片数据集

from matplotlib import pyplot as plt
images_and_labels = list(zip(digits.images, digits.target))
plt.figure(figsize=(8,6), dpi=200)
for index, (image, label) in enumerate(images_and_labels[:8]):
    plt.subplot(2, 4, index+1)
    plt.axis('off')
    plt.imshow(image, cmap=plt.cm.gray_r, interpolation='nearest')
    plt.title('Digit: %i' %label, fontsize=20)

#将数据集分成训练集和测试集，其中20%作为测试数据集
plt.show()
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split

Xtrain, Xtest, Ytrain, Ytest = train_test_split(digits.data, digits.target, test_size=0.2, random_state=2)    #X为图片数据，Y为标记

#选择支持向量机来训练模型

from sklearn import svm

clf = svm.SVC(gamma=0.001, C=100.)
clf.fit(Xtrain, Ytrain);        #fit(训练集样本，训练集标记)

#模型测试，返回正确率
clf.score(Xtest, Ytest)        #score(测试集样本，测试集标记)
